package initializer;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import utils.FileAnalyzer;

import database.mediator.MediatorInterface;
import distributedRE.model.DataBase;

public class DocumentsInitializer implements Initializer{

	private ArrayList<DataBase> databases;
	private long nextId;
	private MediatorInterface mI;
	private long id;
	private String newName;

	public DocumentsInitializer(ArrayList<DataBase> databases, long nextId, String newName){
		this.databases = databases;
		this.nextId = nextId;
		this.newName = newName;
	}
	
	public void Initialize(MediatorInterface mI) {
		
		this.mI = mI;
		
		
		for (DataBase database : databases) {
		
			id = database.getId();
			
			writeDocumentsForDatabase(new File(database.getLocalPath()));
			
		}
		
	}

	private void writeDocumentsForDatabase(File file) {
		
		if (file.isDirectory()) {			  // if a directory
		      String[] files = file.list();		  // list its files
		      Arrays.sort(files);			  // sort the files
		      for (int i = 0; i < files.length; i++)	  // recursively index them
		        writeDocumentsForDatabase(file);

		 } else if (FileAnalyzer.isSummarizable(file,newName)){// index .html or .htm files
		      
			System.out.println("Adding: " + file);
			 
			mI.writeDocument(nextId++,file.getAbsolutePath(),id);

		 }
	}
	
}
